﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
using System.Configuration;

using MINERP.DAL;
using MINERP.MODEL.InfoConfig;
using System.Data.SqlClient;
using MINERP.COM;
using MINERP.MODEL.FoundationModel;

namespace MINERP.BLL.InfoConfig
{
    public class ShopBLL
    {

        #region //Private Fields


        #endregion


        #region //Public Properties

        #endregion



        #region //Public Methods
        /// <summary>
        /// Get shop list
        /// </summary>
        /// <returns></returns>
        public List<Shop> GetShopList()
        {
            using(newSampleYPDBEntities entities = new newSampleYPDBEntities())
            {
                List<Shop> list = entities.Shop.ToList();
                foreach (var item in list)
                {
                    if (!item.shop_DistributionInfoReference.IsLoaded)
                    {
                        item.shop_DistributionInfoReference.Load();
                    }
                }
                return list;
            }
        }

        /// <summary>
        /// Get shop object
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Shop GetShopObj(int id)
        {
            using (newSampleYPDBEntities entities = new newSampleYPDBEntities())
            {
                return entities.Shop.Include("shop_DistributionInfo").FirstOrDefault(s => s.ShopId == id);
          
            }
            //return ShopDAL.GetShopObj(id);
        }

        public Shop GetShopObj(string name)
        {
            using (newSampleYPDBEntities entities = new newSampleYPDBEntities())
            {
                return entities.Shop.FirstOrDefault(s => s.shopName == name);
            }
        }

        /// <summary>
        /// Add shop
        /// </summary>
        /// <param name="obj"></param>
        public void AddShop(Shop obj,List<ProductEntity> list, string ftpLoginId,string ftpPwd)
        {
            //using (newSampleYPDBEntities Entities = new newSampleYPDBEntities())
            //{
            //    foreach (var item in list)
            //    {
            //        Shop_Product_Price spp = new Shop_Product_Price();
            //        spp.AppendPrice = item.AppendPrice;
            //        spp.AreaPrice = (double)obj.AreaPrice;
            //        spp.UnitPrice = item.UnitPrice;
            //        spp.Tb_Product = Entities.Tb_Product.FirstOrDefault(p => p.ProuctId == item.ProuctId);

            //        spp.paperFace = Entities.paperFace.FirstOrDefault(p => p.Name == item.PaperFaceName);
            //        spp.paperType = Entities.paperType.FirstOrDefault(p => p.Name == item.PaperTypeName);
            //        obj.Shop_Product_Price.Add(spp);
            //    }

            //    Entities.AddToShop(obj);

            //    //if (ftpLoginId != string.Empty)
            //    //{
            //    //    CreateFtpAccount(Entities, obj, ftpLoginId, ftpPwd,);
            //    //}
            //    Entities.SaveChanges();
                
            //}

        }

        /// <summary>
        /// Update shop
        /// </summary>
        /// <param name="obj"></param>
        public void UpdateShop(Shop obj, decimal areaPrice, List<ProductEntity> productList, shop_DistributionInfo shop_DistributionInfo)
        {
            //List<ProductEntity> productEntityList = productList.Where(p => p.Status != EnumShopProductStatus.unChange).ToList();
            //using (newSampleYPDBEntities Entities = new newSampleYPDBEntities())
            //{
               
            //    Shop shop = Entities.Shop.FirstOrDefault(s => s.ShopId == obj.ShopId);
            //    if (shop.XmlVersion == null)
            //    {
            //        shop.XmlVersion = 0;
            //    }
            //    shop.XmlVersion += 1;

            //    shop.shopName = obj.shopName;
            //    shop.shopKeeper = obj.shopKeeper;
            //    shop.Tel1 = obj.Tel1;
            //    shop.Tel2 = obj.Tel2;
            //    shop.mnemonicCode = obj.mnemonicCode;
            //    shop.address = obj.address;
            //    shop.EmailAddr = obj.EmailAddr;
            //    shop.Remark = obj.Remark;
            //    shop.Salesman = obj.Salesman;
            //    shop.Area = obj.Area;
            //    shop.CreditLevel = obj.CreditLevel;
            //    shop.QQ = obj.QQ;
            //    shop.MSN = obj.MSN;
            //    shop.IsNeedPrintUPrice = obj.IsNeedPrintUPrice;
            //    shop.PaperFaceId = obj.PaperFaceId;
            //    shop.PaperTypeId = obj.PaperTypeId;
            //    shop.Priority = obj.Priority;
            //    shop.FtpLoginName = obj.FtpLoginName;
            //    shop.FtpLoginPWD = obj.FtpLoginPWD;

            //    if (!shop.shop_DistributionInfoReference.IsLoaded)
            //    {
            //        shop.shop_DistributionInfoReference.Load();
            //    }
            //    shop.shop_DistributionInfo.BusTimetable = shop_DistributionInfo.BusTimetable;
            //    shop.shop_DistributionInfo.ConsigneeName = shop_DistributionInfo.ConsigneeName;
            //    shop.shop_DistributionInfo.ConsigneeTelePhone = shop_DistributionInfo.ConsigneeTelePhone;
            //    shop.shop_DistributionInfo.DistributionAddress = shop_DistributionInfo.DistributionAddress;
            //    shop.shop_DistributionInfo.DistributionMode = shop_DistributionInfo.DistributionMode;
            //    shop.shop_DistributionInfo.FarePayer = shop_DistributionInfo.FarePayer;
            //    shop.shop_DistributionInfo.ReMark = shop_DistributionInfo.ReMark;

            //    if (!shop.Shop_Product_Price.IsLoaded)
            //    {
            //        shop.Shop_Product_Price.Load();
            //    }
            //    foreach (var sp in shop.Shop_Product_Price)
            //    {
            //        if (!sp.Tb_ProductReference.IsLoaded)
            //        {
            //            sp.Tb_ProductReference.Load();
            //        }
            //    }

            //    if (shop != null)
            //    {
            //        foreach (var item in productEntityList)
            //        {
            //            switch (item.Status)
            //            {
            //                case EnumShopProductStatus.add:
            //                    Shop_Product_Price spp = new Shop_Product_Price();
            //                    spp.AppendPrice = item.AppendPrice;
            //                    //if (areaPrice ==(decimal)item.AreaPrice)
            //                    //{
            //                    //    spp.AreaPrice = (double)areaPrice;
            //                    //}
            //                    //else
            //                    //{
            //                    //    spp.AreaPrice = item.AreaPrice;
            //                    //}
            //                    spp.AreaPrice = item.AreaPrice;
            //                    spp.UnitPrice = item.UnitPrice;
            //                    spp.Tb_Product = Entities.Tb_Product.FirstOrDefault(p => p.ProuctId == item.ProuctId);
            //                    spp.paperFace = Entities.paperFace.FirstOrDefault(p => p.PaperFaceID == obj.PaperFaceId);
            //                    spp.paperType = Entities.paperType.FirstOrDefault(p => p.PaperTypeID == obj.PaperTypeId);
            //                    shop.Shop_Product_Price.Add(spp);
            //                    Entities.SaveChanges();
            //                    item.Status = EnumShopProductStatus.update;
            //                    item.IsShopProduct = true;
            //                    break;
            //                case EnumShopProductStatus.update:
            //                    Shop_Product_Price sppTemp = shop.Shop_Product_Price.FirstOrDefault(s => s.Tb_Product.ProuctId == item.ProuctId);
            //                    if (sppTemp.AppendPrice != item.AppendPrice || sppTemp.UnitPrice != item.UnitPrice || sppTemp.AreaPrice != (double)areaPrice || sppTemp.AreaPrice != item.AreaPrice)
            //                    {
            //                        sppTemp.AppendPrice = item.AppendPrice;
            //                        //if (obj.AreaPrice ==(decimal)sppTemp.AreaPrice)
            //                        //{
            //                        //    sppTemp.AreaPrice = (double)areaPrice;
            //                        //}
            //                        //else
            //                        //{
            //                        //    sppTemp.AreaPrice = item.AreaPrice;
            //                        //}
            //                        sppTemp.AreaPrice = item.AreaPrice;
            //                        sppTemp.UnitPrice = item.UnitPrice;
            //                        sppTemp.Tb_Product = Entities.Tb_Product.FirstOrDefault(p => p.ProuctId == item.ProuctId);
            //                        sppTemp.paperFace = Entities.paperFace.FirstOrDefault(p => p.PaperFaceID == obj.PaperFaceId);
            //                        sppTemp.paperType = Entities.paperType.FirstOrDefault(p => p.PaperTypeID == obj.PaperTypeId);
            //                    }
            //                    break;
            //                case EnumShopProductStatus.delete:
            //                    if (item.IsShopProduct)
            //                    {
            //                        Shop_Product_Price shopProduct = shop.Shop_Product_Price.FirstOrDefault(s => s.Tb_Product.ProuctId == item.ProuctId);
            //                        //if (shopProduct != null)
            //                        //{
            //                        shop.Shop_Product_Price.Remove(shopProduct);
            //                        Entities.SaveChanges();
            //                        item.IsShopProduct = false;
            //                        //}
            //                    }
            //                    break;
            //            }
            //        }
                    
            //    }
            //    shop.AreaPrice = areaPrice;
            //    Entities.SaveChanges();
            //}
        }

        /// <summary>
        /// Delete shop
        /// </summary>
        /// <param name="obj"></param>
        public void DeleteShop(Shop obj)
        {
            using (newSampleYPDBEntities Entities = new newSampleYPDBEntities())
            {
                Shop shop = Entities.Shop.FirstOrDefault(s => s.ShopId == obj.ShopId);
                shop.Status = 0;
                Entities.SaveChanges();

            }
        }

        /// <summary>
        /// resume shop
        /// </summary>
        /// <param name="obj"></param>
        public void Resume(Shop obj)
        {
            using (newSampleYPDBEntities Entities = new newSampleYPDBEntities())
            {
                Shop shop = Entities.Shop.FirstOrDefault(s => s.ShopId == obj.ShopId);
                shop.Status = 1;
                Entities.SaveChanges();

            }
        }

        public SUUsers GetSUUser(Shop shop)
        {
            using (newSampleYPDBEntities entities = new newSampleYPDBEntities())
            {
                return entities.SUUsers.FirstOrDefault(s => s.ShopId == shop.ShopId);
            }
        }

        public void SetFtp(bool flag, Shop shop, string ftpLoginId, string ftpPwd,string shopLoginid,string shopLoginPwd)
        {
            using (newSampleYPDBEntities entities = new newSampleYPDBEntities())
            {
               SUUsers suuser = entities.SUUsers.FirstOrDefault(s => s.ShopId ==shop.ShopId);
               if (suuser != null)
               {
                   if (flag)
                   {
                       suuser.Enabled = "1";
                   }
                   else
                   {
                       suuser.Enabled = "0";
                   }
                   entities.SaveChanges();
               }
               else
               {
                   CreateFtpAccount(entities,shop,ftpLoginId,ftpPwd,shopLoginid,shopLoginPwd);
                   entities.SaveChanges();
               }
            }
        }

        public bool ExportProductsToXml(Shop obj)
        {

            using (newSampleYPDBEntities entities = new newSampleYPDBEntities())
            {
                DataSet ds = GetProducts(obj);
                SUUsers suuser =entities.SUUsers.FirstOrDefault(s=>s.ShopId ==obj.ShopId);
                if (suuser == null)
                {
                    return false;
                }
                ds.WriteXml(suuser.HomeDir + "\\" + "product.Xml",XmlWriteMode.WriteSchema);
                return true;
            }



        }

        private DataSet GetProducts(Shop obj)
        {
            //string conStr = ConfigurationManager.ConnectionStrings["fffff"].ToString();
            string conStr = DALBase.ConnStr;
            using (SqlConnection con = new SqlConnection(conStr))
            {
                StringBuilder sql = new StringBuilder();
                sql.Append("select  tb_product.ProuctId as ProductId,ProductName,tb_product.Width,tb_product.Height,PageNum,Tb_PorductCategory.ProductCategoryId,ProductCategoryName,UsedTimes=0,");
                sql.Append(" ProductTypeCode as ProductTypeRemark,");
                sql.Append(" tb_product.mnemonicCode as ZJCode");
                sql.Append(" from Shop_Product_Price inner join  tb_product on Shop_Product_Price.ProductId=tb_product.ProuctId inner join Tb_PorductCategory on tb_product.ProductCategoryId=Tb_PorductCategory.ProductCategoryId");
                sql.Append(" inner join tb_ProductType on tb_product.PorductTypeId=tb_ProductType.ProductTypeId  ");

                sql.Append(" where Shop_Product_Price.shopid=" + obj.ShopId);
                DataTable dt = new DataTable("products");
                SqlCommand cmd = new SqlCommand(sql.ToString(), con);
                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                con.Open();
                adapter.Fill(dt);

                string sqlPaperFace = "select PaperFaceId,Name as PaperFaceName from paperface";
                cmd.CommandText = sqlPaperFace;
                SqlDataAdapter apapter2 = new SqlDataAdapter(cmd);
                DataTable dt2 = new DataTable("paperFace");
                apapter2.Fill(dt2);

                DataSet ds = new DataSet();
                ds.Tables.Add(dt);
                ds.Tables.Add(dt2);
                return ds;
            }
        }
        public DataTable CreateDataTable()
        {
            DataTable dt = new DataTable("ProductsTable");
            dt.Columns.Add("ProuctId",typeof(int));
            dt.Columns.Add("ProductName",typeof(string));
            dt.Columns.Add("ProductCategoryName",typeof(string));
            return dt;
        }

        public bool IsFtpLoginIdExist(string ftpLoginId,Shop shop)
        {
            using (newSampleYPDBEntities entities = new newSampleYPDBEntities())
            {
                SUUsers su = entities.SUUsers.FirstOrDefault(s => s.LoginID == ftpLoginId);
                if (su != null&&su.ShopId !=shop.ShopId)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        public bool IsShopLoginIdExist(string shopLoginid,Shop obj)
        {
            using (newSampleYPDBEntities entities = new newSampleYPDBEntities())
            {
                Shop shop = entities.Shop.FirstOrDefault(s => s.FtpLoginName == shopLoginid);
                if(shop!=null&&shop.ShopId !=obj.ShopId)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
        private void CreateFtpAccount(newSampleYPDBEntities Entities, Shop obj, string ftpLoginId, string ftpPwd,string shopLoginId,string shopLoginPwd)
        {
            Shop shop = Entities.Shop.FirstOrDefault(s => s.ShopId == obj.ShopId);
            shop.FtpLoginName = shopLoginId;
            shop.FtpLoginPWD = shopLoginPwd;

            FileDirPath ftpfilePath = Entities.FileDirPath.FirstOrDefault(f => f.Des == "Ftp文件根目录");
            SUUsers suuser = new SUUsers();
            suuser.ShopId = Entities.Shop.FirstOrDefault(s => s.shopName == obj.shopName).ShopId;
            suuser.LoginID = ftpLoginId;
            suuser.Password = ftpPwd;
            suuser.AlwaysAllowLogin = "1";
            suuser.LockInHomeDir = "1";
            suuser.PasswordEncryptMode = "0";
            suuser.HomeDir = ftpfilePath.FileDir + "\\" + obj.shopName;
            Entities.AddToSUUsers(suuser);

            UserDirAccess userDir = new UserDirAccess();
            userDir.LoginID = ftpLoginId;
            userDir.SortIndex = 1;
            userDir.Access = "7967";
            userDir.NTPassword = "_207c4dd8d3bad015";
            userDir.Dir = suuser.HomeDir;
            Entities.AddToUserDirAccess(userDir);

            if (!Directory.Exists(ftpfilePath.FileDir + "\\" + obj.shopName))
            {
                Directory.CreateDirectory(ftpfilePath.FileDir + "\\" + obj.shopName);
            }
        }

        public List<ProductEntity> GetProductList(Shop obj)
        {
            //List<ProductEntity> list = new List<ProductEntity>();
            //using (newSampleYPDBEntities entities = new newSampleYPDBEntities())
            //{
            //    Shop shop = entities.Shop.FirstOrDefault(s => s.ShopId == obj.ShopId);
            //    if (!shop.Shop_Product_Price.IsLoaded)
            //    {
            //        shop.Shop_Product_Price.Load();
            //    }
            //    List<Tb_Product> productList = entities.Tb_Product.Where(p=>p.Status !=0).ToList();
            //    foreach (var product in productList)
            //    {
            //        ProductEntity productEntity = new ProductEntity();
            //        if (!product.paperFaceReference.IsLoaded)
            //        {
            //            product.paperFaceReference.Load();
            //        }
            //        if (!product.paperTypeReference.IsLoaded)
            //        {
            //            product.paperTypeReference.Load();
            //        }
            //        if (!product.Tb_PorductCategoryReference.IsLoaded)
            //        {
            //            product.Tb_PorductCategoryReference.Load();
            //        }
            //        if (!product.tb_ProductTypeReference.IsLoaded)
            //        {
            //            product.tb_ProductTypeReference.Load();
            //        }
            //        if (!product.tb_CostTypeReference.IsLoaded)
            //        {
            //            product.tb_CostTypeReference.Load();
            //        }
            //        productEntity.Height = product.Height;
            //        productEntity.PageNum = product.PageNum;
            //        productEntity.PaperFaceID = product.paperFace.PaperFaceID;
            //        productEntity.PaperFaceName = product.paperFace.Name;
            //        productEntity.PaperTypeID = product.paperType.PaperTypeID;
            //        productEntity.PaperTypeName = product.paperType.Name;
            //        productEntity.ProductCategoryId = product.Tb_PorductCategory.ProductCategoryId;
            //        productEntity.ProductCategoryName = product.Tb_PorductCategory.ProductCategoryName;
            //        productEntity.ProductTypeName = product.tb_ProductType.TypeName;
            //        productEntity.CostTypeName = product.tb_CostType.TypeName;
            //        productEntity.ProductCode = product.ProductCode;
            //        productEntity.ProductDes = product.ProductDes;
            //        productEntity.ProductName = product.ProductName;
            //        productEntity.UnitPrice = product.UnitPrice;
            //        productEntity.AppendPrice = product.AppendPrice;
            //        productEntity.AreaPrice = product.AreaPrice;
            //        productEntity.ProuctId = product.ProuctId;
            //        productEntity.Width = product.Width;
            //        productEntity.Status = EnumShopProductStatus.unChange;
            //        foreach (var item in shop.Shop_Product_Price)
            //        {
            //            if (item.ProductId == product.ProuctId)
            //            {
            //                productEntity.AppendPrice = item.AppendPrice;
            //                productEntity.AreaPrice = item.AreaPrice;
            //                productEntity.UnitPrice = item.UnitPrice;
            //                productEntity.IsChecked = true;
            //                //productEntity.Status = EnumShopProductStatus.update;
            //                productEntity.IsShopProduct = true;
            //                break;
            //            }
            //            else
            //            {
            //                //productEntity.Status = EnumShopProductStatus.delete;
            //                productEntity.IsShopProduct = false;
            //            }
            //        }
            //        list.Add(productEntity);
            //    }
            //}
            //return list;
            return new List<ProductEntity>();
        }

        public List<ProductEntity> GetProductList()
        {
            List<ProductEntity> list = new List<ProductEntity>();
            using (newSampleYPDBEntities entities = new newSampleYPDBEntities())
            {
                List<Tb_Product> productList = entities.Tb_Product.Where(p => p.Status != 0).ToList();
                foreach (var product in productList)
                {
                    ProductEntity productEntity = new ProductEntity();
                    if (!product.paperFaceReference.IsLoaded)
                    {
                        product.paperFaceReference.Load();
                    }
                    if (!product.paperTypeReference.IsLoaded)
                    {
                        product.paperTypeReference.Load();
                    }
                    if (!product.Tb_PorductCategoryReference.IsLoaded)
                    {
                        product.Tb_PorductCategoryReference.Load();
                    }
                    if (!product.tb_ProductTypeReference.IsLoaded)
                    {
                        product.tb_ProductTypeReference.Load();
                    }
                    if (!product.tb_CostTypeReference.IsLoaded)
                    {
                        product.tb_CostTypeReference.Load();
                    }
                    productEntity.Height = product.Height;
                    productEntity.PageNum = product.PageNum;
                    productEntity.PaperFaceID = product.paperFace.PaperFaceID;
                    productEntity.PaperFaceName = product.paperFace.Name;
                    productEntity.PaperTypeID = product.paperType.PaperTypeID;
                    productEntity.PaperTypeName = product.paperType.Name;
                    productEntity.ProductCategoryId = product.Tb_PorductCategory.ProductCategoryId;
                    productEntity.ProductCategoryName = product.Tb_PorductCategory.ProductCategoryName;
                    productEntity.ProductTypeName = product.tb_ProductType.TypeName;
                    productEntity.CostTypeName = product.tb_CostType.TypeName;
                    productEntity.ProductCode = product.ProductCode;
                    productEntity.ProductDes = product.ProductDes;
                    productEntity.ProductName = product.ProductName;
                    productEntity.UnitPrice = product.UnitPrice;
                    productEntity.AppendPrice = product.AppendPrice;
                    productEntity.AreaPrice = product.AreaPrice;
                    productEntity.ProuctId = product.ProuctId;
                    productEntity.Width = product.Width;
                    list.Add(productEntity);
                }
            }
            return list;
        }
        //修改产品平米价
        public void UpdateAreaPrice(Shop shop, double areaPrice)
        {
            //using (newSampleYPDBEntities entities = new newSampleYPDBEntities())
            //{
            //    Shop sp = entities.Shop.FirstOrDefault(s => s.ShopId == shop.ShopId);
            //    sp.AreaPrice = (decimal)areaPrice;
            //    if (sp != null)
            //    {
            //        if (!sp.Shop_Product_Price.IsLoaded)
            //        {
            //            sp.Shop_Product_Price.Load();
            //        }
            //        foreach (var item in sp.Shop_Product_Price)
            //        {
            //            item.AreaPrice = areaPrice;
            //        }
            //    }
            //    entities.SaveChanges();
            //}
        }
        public List<Shop_Info> GetShopInfoByHelpCode(string inHelpCode)
        {
            List<Shop_Info> shopInfoList = new List<Shop_Info>();
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                List<Shop> listShop = db.Shop.Where(p => p.mnemonicCode.Contains(inHelpCode)).ToList();
                listShop.ForEach(s => shopInfoList.Add(new Shop_Info()
                {
                    Address = s.address,
                    Area = s.Area,
                    ShopKeeper = s.shopKeeper,
                    CreditLevel = s.CreditLevel ?? 0,
                    EmailAddr = s.EmailAddr,
                    MnemonicCode = s.mnemonicCode,
                    IsNeedPrintUPrice = s.IsNeedPrintUPrice ?? false,
                    MSN = s.MSN,
                    Tel1 = s.Tel1,
                    Tel2 = s.Tel2,
                    //PaperFaceID = s.PaperFaceId ?? 0,
                    //PaperTypeID = s.PaperTypeId ?? 0,

                    Salesman = s.Salesman,
                    Priority = s.Priority ?? 0,
                    QQ = s.QQ,
                    Remark = s.Remark,
                    ShopId = s.ShopId,
                    ShopName = s.shopName,
                    Status = s.Status ?? 0,


                }));

            }
            return shopInfoList;
        }
        #endregion
    }
}
